# 独立使用django的model
import sys
import os
import random

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + "../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "League_of_Legends.settings")

import django

django.setup()

from apps.goods.models import GoodsCateogory, Goods, Category, GoodsImage
from db_tools.data.GoodsCategory import row_data_cat  # 分类
from db_tools.data.Goods_data import row_data_goods  # 商品

i = 1
for lev1_cat in row_data_goods:
    goods = Goods()  # 商品对象
    cat = Category()  # 分类表对象
    goods.id = i + 1  # 设置主键
    goods.name = lev1_cat["sMallName"]  # 商品名称
    lev1_cat["iVipPrice"] = int(lev1_cat["iVipPrice"]) / 100  # 商品原价
    lev1_cat["iPrice"] = int(lev1_cat["iPrice"]) / 100 - random.randint(8, 11)  # 商品现价
    # print(lev1_cat["iVipPrice"], "-------------------------------------")   # 打印用的
    # print(lev1_cat["iPrice"], "-------------------------------------")
    goods.current_price = str(lev1_cat["iVipPrice"])
    goods.original_price = str(lev1_cat["iPrice"])
    goods.front_image = lev1_cat["sProfileImg"]  # 封面图

    parent_id = None
    for category in row_data_cat:  # 循环分类数据
        i += 1
        Goods_cat = GoodsCateogory()  # 商品分类对象
        cat = Category()  # 分类表对象
        Goods_cat.name = category['sCatName']  # 分类名称
        Goods_cat.image = category['sCatIcon2']  # 分类封面图
        Goods_cat.id = int(category["iCatId"])  # 商品分类的id
        if category['iParentId'] != '0':

            try:
                Goods_cat.parent_category = GoodsCateogory.objects.get(id=int(category['iParentId']))
            except GoodsCateogory.DoesNotExist:
                print("当前没有父类")
                continue  # 2级分类没有获取到父类，就继续添加
            else:
                print("获取到了父类")
            if lev1_cat['iCatId'] == category['iCatId']:
                cat.category = Goods_cat  # 绑定分类数据
                cat.goods = goods  # 绑定商品数据
                Goods_cat.save()  # 保存商品分类表
                goods.save()  # 保存商品表
                cat.save()  # 保存分类表

                for lev2_cat in lev1_cat["sDetailImg"]:
                    # 实例出商品详情图对象
                    goods_image = GoodsImage()

                    goods_image.goods = goods
                    goods_image.image = lev2_cat  # 详情图
                    goods_image.save()
